package com.tongda.core.utils;

/**
 * 
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

import com.tongda.core.service.BaseService;

/**
 * @author andy
 * 
 */
public class CommunicationUtil {

	public static String SESSION_ID = "";

	/**
	 * get方式获取响应类容
	 * 
	 * @param uri
	 * @return
	 */
	public static String get(String uri) {
		BufferedReader reader = null;
		StringBuffer sb = null;
		String result = "";
		HttpClient client = new DefaultHttpClient();
		HttpParams params = client.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 6000);
		HttpConnectionParams.setSoTimeout(params, 8000);
		HttpGet request = new HttpGet(uri);
		request.setHeader("Cookie", BaseService.COOKIE_STR + addSessionId());
		try {
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				reader = new BufferedReader(new InputStreamReader(response
						.getEntity().getContent(), "UTF-8"));
				sb = new StringBuffer();
				String line = "";
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
			}
		} catch (Exception e) {
			Log.i("CommunicationUtil.get", uri + " --unreachable");
		} finally {
			try {
				if (null != reader) {
					reader.close();
					reader = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (null != sb) {
			result = sb.toString();
		}
		return result;
	}

	/**
	 * post方式获取响应类容
	 * 
	 * @param uri
	 * @return
	 */
	public static String post(String uri, Map<Object, Object> parameters) {
		BufferedReader reader = null;
		StringBuffer sb = null;
		String result = "";
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(uri);

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		Set<Object> k = parameters.keySet();
		for (Iterator iterator = k.iterator(); iterator.hasNext();) {
			Object key = (Object) iterator.next();
			Object value = parameters.get(key);
			if (value != null) {
				params.add(new BasicNameValuePair(key.toString(), value
						.toString()));
			} else {
				params.add(new BasicNameValuePair(key.toString(), null));
			}
		}

		try {
			HttpEntity entity = new UrlEncodedFormEntity(params, "utf-8");
			request.setEntity(entity);
			request.setHeader("Cookie", BaseService.COOKIE_STR);
			HttpResponse response = client.execute(request);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				reader = new BufferedReader(new InputStreamReader(response
						.getEntity().getContent()));
				sb = new StringBuffer();
				String line = "";
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				// session
				Header[] Headers = response.getHeaders("JSESSIONID");
				for (Header h : Headers) {
					if ("JSESSIONID".equals(h.getName())) {
						String SESSION_ID_TEMP = h.getValue();
						if (SESSION_ID_TEMP != "" && SESSION_ID_TEMP != null)
							SESSION_ID = SESSION_ID_TEMP;
					}
				}

			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != reader) {
					reader.close();
					reader = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (null != sb) {
			result = sb.toString();
		}
		return result;
	}

	static String what = "";

	public static String getByServerIpScanner(final String uri) {
		Thread subThread = new Thread() {
			@Override
			public void run() {
				super.run();
				StringBuffer sb = null;
				BufferedReader reader = null;
				HttpClient client = new DefaultHttpClient();
				HttpGet request = new HttpGet(uri);
				request.setHeader("Cookie", BaseService.COOKIE_STR);
				HttpResponse response = null;
				try {
					response = client.execute(request);
				} catch (Exception e) {
					response = null;
					what = "";
				} finally {
					try {
						if (response != null
								&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
							reader = new BufferedReader(new InputStreamReader(
									response.getEntity().getContent(), "UTF-8"));
							sb = new StringBuffer();
							String line = "";
							while ((line = reader.readLine()) != null) {
								sb.append(line);
							}
							reader.close();
						}
					} catch (Exception e) {
						response = null;
						what = "";
					}
					if (null != sb) {
						what = sb.toString();
					}
					;
				}
			}
		};
		subThread.start();
		try {
			subThread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return what;
	}

	private static String addSessionId() {
		if (CommunicationUtil.SESSION_ID != ""
				&& CommunicationUtil.SESSION_ID != null) {
			return ";JSESSIONID=" + CommunicationUtil.SESSION_ID;
		}
		return "";
	}
}
